package com.hfy.admin.service.impl;

import beans.mybatis.user.mapper.PostDataMapper;
import beans.mybatis.user.mapper.PostMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.hfy.admin.service.PostManagementService;
import com.hfy.model.Es.PostES;
import com.hfy.model.po.user.post.PostDataPo;
import com.hfy.model.po.user.post.PostPo;
import com.hfy.model.vo.post.IndexShowPostVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import result.Result;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ author 韩
 * time: 2025/1/4 0:37
 */
@Service
public class PostManagementServiceImpl implements PostManagementService {

    @Autowired
    private PostMapper postMapper;
    
    @Autowired
    private PostDataMapper postDataMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Result pagePostsByFilters(Integer pageNum, Integer pageSize , String title, Integer topicId, LocalDateTime startTime, LocalDateTime endTime, Integer startLikeNum, Integer endLikeNum, Integer startCollectNum, Integer endCollectNum, Integer startViewNum, Integer endViewNum, Integer startWordNum, Integer endWordNum, String contentKey, Boolean isNameless, Boolean isDie) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // 动态添加筛选条件
        if (topicId != null) {
            queryBuilder.must(QueryBuilders.termQuery("topicId", topicId));
        }
        if (org.apache.commons.lang.StringUtils.isBlank(title)) {
            queryBuilder.must(QueryBuilders.termQuery("title", title));
        }
        if (startTime != null || endTime != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime");
            if (startTime != null) {
                rangeQuery.gte(startTime.toString());
            }
            if (endTime != null) {
                rangeQuery.lte(endTime.toString());
            }
            queryBuilder.must(rangeQuery);
        }
        if (startLikeNum != null || endLikeNum != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("likeNum");
            if (startLikeNum != null) {
                rangeQuery.gte(startLikeNum);
            }
            if (endLikeNum != null) {
                rangeQuery.lte(endLikeNum);
            }
            queryBuilder.must(rangeQuery);
        }
        if (startCollectNum != null || endCollectNum != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("collectNum");
            if (startCollectNum != null) {
                rangeQuery.gte(startCollectNum);
            }
            if (endCollectNum != null) {
                rangeQuery.lte(endCollectNum);
            }
            queryBuilder.must(rangeQuery);
        }
        if (startViewNum != null || endViewNum != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("viewNum");
            if (startViewNum != null) {
                rangeQuery.gte(startViewNum);
            }
            if (endViewNum != null) {
                rangeQuery.lte(endViewNum);
            }
            queryBuilder.must(rangeQuery);
        }
        if (startWordNum != null || endWordNum != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("wordNum");
            if (startWordNum != null) {
                rangeQuery.gte(startWordNum);
            }
            if (endWordNum != null) {
                rangeQuery.lte(endWordNum);
            }
            queryBuilder.must(rangeQuery);
        }
        if (contentKey != null && !contentKey.isBlank()) {
            queryBuilder.must(QueryBuilders.matchQuery("contentText", contentKey));
        }
        if (isNameless != null) {
            queryBuilder.must(QueryBuilders.termQuery("isNameless", isNameless));
        }
        if (isDie != null) {
            queryBuilder.must(QueryBuilders.termQuery("isDie", isDie));
        }

        // 设置分页
        int from = pageSize * pageNum;

        // 构造查询请求
        SearchRequest searchRequest = new SearchRequest("post");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        sourceBuilder.from(from);
        sourceBuilder.size(pageSize);
        searchRequest.source(sourceBuilder);

        // 执行查询
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取总数
        long total = searchResponse.getHits().getTotalHits().value;


        // 解析查询结果
        List<PostES> posts = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            PostES post = JSON.parseObject(hit.getSourceAsString(), PostES.class);
            posts.add(post);
        }
        // 包装分页结果
        Page<PostES> voPage = new Page<>();
        voPage.setRecords(posts);
        voPage.setCurrent(pageNum);  // 当前页码
        voPage.setSize(pageSize);     // 每页条数
        voPage.setTotal(total);   // 总记录数


        return Result.ok(voPage);
    }

    @Override
    @DS("user")
    public Result searchPosts(String type, String value, LocalDateTime startTime, LocalDateTime endTime) {
        // 构建查询条件
        LambdaQueryWrapper<PostPo> postWrapper = new LambdaQueryWrapper<>();
        
        // 根据搜索类型添加条件
        if (StringUtils.isNotBlank(value)) {
            switch (type) {
                case "id":
                    try {
                        Integer postId = Integer.parseInt(value);
                        postWrapper.eq(PostPo::getId, postId);
                    } catch (NumberFormatException e) {
                        return Result.error("帖子ID必须是数字");
                    }
                    break;
                case "title":
                    // 由于标题实际上是在PostData表中的contentText字段
                    // 我们需要先查询PostData表，然后再关联Post表
                    List<Integer> postIds = postDataMapper.findPostIdsByContentText(value);
                    if (postIds.isEmpty()) {
                        return Result.ok(new ArrayList<>());
                    }
                    postWrapper.in(PostPo::getId, postIds);
                    break;
                case "author":
                    postWrapper.like(PostPo::getNickname, value)
                            .or()
                            .like(PostPo::getAccount, value);
                    break;
                default:
                    return Result.error("不支持的搜索类型");
            }
        }
        
        // 添加时间范围条件
        if (startTime != null) {
            postWrapper.ge(PostPo::getCreateTime, startTime);
        }
        if (endTime != null) {
            postWrapper.le(PostPo::getCreateTime, endTime);
        }
        
        // 只查询未删除的帖子
        postWrapper.eq(PostPo::getIsDie, false);
        
        // 执行查询
        List<PostPo> posts = postMapper.selectList(postWrapper);
        if (posts.isEmpty()) {
            return Result.ok(new ArrayList<>());
        }
        
        // 获取帖子ID列表
        List<Integer> postIdList = posts.stream()
                .map(PostPo::getId)
                .collect(Collectors.toList());
        
        // 查询帖子数据
        List<PostDataPo> postDataList = postDataMapper.selectByPostIds(postIdList);
        
        // 组装返回结果
        List<IndexShowPostVo> result = new ArrayList<>();
        for (PostPo post : posts) {
            PostDataPo postData = postDataList.stream()
                    .filter(data -> data.getPostId().equals(post.getId()))
                    .findFirst()
                    .orElse(null);

            if (postData != null) {
                IndexShowPostVo vo = new IndexShowPostVo();
                vo.setId(post.getId());
                vo.setAccount(post.getAccount());
                vo.setNickname(post.getNickname());
                vo.setAvatar(post.getAvatar());
                vo.setWeight(postData.getWeight());
                vo.setTopicId(post.getTopicId());
                vo.setCreateTime(post.getCreateTime());
                vo.setIsNameless(post.getIsNameless());
                vo.setAccount(post.getAccount());
                vo.setContent(postData.getContentText());
                vo.setWordNum(postData.getWordNum());
                vo.setLikeNum(postData.getLikeNum());
                vo.setCommentNum(postData.getCommentNum());
                vo.setCollectNum(postData.getCollectNum());
                vo.setShareNum(postData.getShareNum());
                vo.setViewNum(postData.getViewNum());
                vo.setHeat(postData.getHeat());
                vo.setIsNameless(post.getIsNameless());
                result.add(vo);
            }
        }

        return Result.ok(result);
    }
    
    @Override
    @DS("user")
    @Transactional
    public Result batchUpdateHot(List<Map<String, Object>> posts) {
        if (posts == null || posts.isEmpty()) {
            return Result.error("请提供要更新的帖子列表");
        }
        
        for (Map<String, Object> post : posts) {
            Integer postId = (Integer) post.get("id");
            Integer hot = (Integer) post.get("hot");
            
            if (postId == null || hot == null) {
                continue;
            }
            
            // 更新帖子热度
            postDataMapper.updateHeat(postId, hot);
        }
        
        return Result.ok("批量更新热度成功");
    }
    
    @Override
    @DS("user")
    @Transactional
    public Result resetPostsHot(List<Integer> postIds) {
        if (postIds == null || postIds.isEmpty()) {
            return Result.error("请提供要重置的帖子ID列表");
        }
        
        // 默认热度值设为100
        final int defaultHot = 100;
        
        for (Integer postId : postIds) {
            postDataMapper.updateHeat(postId, defaultHot);
        }
        
        return Result.ok("重置热度成功");
    }
}
